package com.kaf.api.controller;

import com.kaf.ai.dto.ChatRequest;
import com.kaf.ai.service.DeepSeekService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@Slf4j
@RestController
public class ChatController {

    private final DeepSeekService deepSeekService;

    public ChatController(DeepSeekService deepSeekService) {
        this.deepSeekService = deepSeekService;
    }

    @PostMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@RequestBody ChatRequest request) {
        return deepSeekService.streamChatCompletion(request)
//                .map(content -> ServerSentEvent.<String>builder().data(content).build())
                .doOnSubscribe(subscription -> log.info("客户端已订阅流"))
                .doOnCancel(() -> log.warn("客户端取消订阅"))
                .doOnError(e -> log.error("控制器流处理错误", e))
                .doOnComplete(() -> log.info("控制器流处理完成"))
                .doFinally(signalType -> log.info("控制器流处理结束，信号类型: {}", signalType));
    }
}
